<template>
  <div class="home">
    <!-- 引用导航栏组件 -->
    <Navbar />

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="container">
        <div class="content-wrapper">
          <!-- 左侧主内容 -->
          <div class="main-left">
            <!-- 幻灯片区域 -->
            <section class="slider-section">
              <div class="slider" v-if="slideVideos.length > 0">
                <div class="slider-item" v-for="(video, index) in slideVideos" :key="video.id">
                  <router-link :to="`/video/${video.id}`" class="slider-link">
                    <img 
                      :src="video.cover_url || '/default-cover.jpg'" 
                      :alt="video.title" 
                      class="slider-img"
                    />
                    <div class="slider-info">
                      <h3 class="slider-title">{{ video.title }}</h3>
                      <div class="slider-stats">
                        <span class="view-count">{{ formatCount(video.view_count) }}播放</span>
                        <span class="duration">{{ video.duration }}</span>
                      </div>
                    </div>
                  </router-link>
                </div>
              </div>
            </section>

            <!-- 功能导航 -->
            <div class="feature-nav">
              <ul class="feature-list">
                <li class="feature-item">
                  <router-link to="/" class="feature-link active">首页</router-link>
                </li>
                <li class="feature-item">
                  <a href="#" class="feature-link">番剧</a>
                </li>
                <li class="feature-item">
                  <a href="#" class="feature-link">排行榜</a>
                </li>
                <li class="feature-item">
                  <a href="#" class="feature-link">动态</a>
                </li>
                <li class="feature-item">
                  <a href="#" class="feature-link">历史</a>
                </li>
                <li class="feature-item">
                  <a href="#" class="feature-link">收藏</a>
                </li>
              </ul>
            </div>

            <!-- 各个分类的视频区域 -->
            <div v-for="category in displayCategories" :key="category.id" class="category-section">
              <div class="section-header">
                <h2 class="section-title">
                  <router-link :to="`/category/${category.id}`" class="category-title-link">
                    {{ category.name }}
                  </router-link>
                </h2>
                <router-link :to="`/category/${category.id}`" class="more-link">查看更多 ></router-link>
              </div>
              <div class="video-grid">
                <VideoCard 
                  v-for="video in getCategoryVideos(category.id)" 
                  :key="video.id"
                  :video="video"
                />
              </div>
            </div>
          </div>

          <!-- 右侧边栏 -->
          <div class="main-right">
            <!-- 推荐视频 -->
            <aside class="recommend-section">
              <div class="sidebar-header">
                <h3 class="sidebar-title">推荐视频</h3>
              </div>
              <div class="video-list">
                <VideoListItem 
                  v-for="video in recommendedVideos" 
                  :key="video.id"
                  :video="video"
                />
              </div>
            </aside>

            <!-- 热门视频 -->
            <aside class="hot-section">
              <div class="sidebar-header">
                <h3 class="sidebar-title">热门视频</h3>
              </div>
              <div class="video-list">
                <VideoListItem 
                  v-for="video in hotVideos" 
                  :key="video.id"
                  :video="video"
                />
              </div>
            </aside>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-links">
            <div class="footer-col">
              <h4>关于我们</h4>
              <ul>
                <li><a href="#">关于哔哩哔哩</a></li>
                <li><a href="#">联系我们</a></li>
                <li><a href="#">加入我们</a></li>
                <li><a href="#">友情链接</a></li>
              </ul>
            </div>
            <div class="footer-col">
              <h4>服务支持</h4>
              <ul>
                <li><a href="#">帮助中心</a></li>
                <li><a href="#">侵权投诉</a></li>
                <li><a href="#">用户反馈</a></li>
                <li><a href="#">用户协议</a></li>
              </ul>
            </div>
            <div class="footer-col">
              <h4>社区</h4>
              <ul>
                <li><a href="#">创作中心</a></li>
                <li><a href="#">直播中心</a></li>
                <li><a href="#">活动中心</a></li>
                <li><a href="#">排行榜</a></li>
              </ul>
            </div>
            <div class="footer-col">
              <h4>客户端下载</h4>
              <ul>
                <li><a href="#">iOS客户端</a></li>
                <li><a href="#">Android客户端</a></li>
                <li><a href="#">PC客户端</a></li>
                <li><a href="#">TV客户端</a></li>
              </ul>
            </div>
          </div>
          <div class="footer-copyright">
            <p>© 2025 Bilibili. All Rights Reserved.</p>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import VideoCard from '../components/VideoCard.vue';
import VideoListItem from '../components/VideoListItem.vue';
import Navbar from '../components/Navbar.vue';
import videoApi from '../api/videoApi';
import categoryApi from '../api/categoryApi';

export default {
  name: 'Home',
  components: {
    VideoCard,
    VideoListItem,
    Navbar
  },
  setup() {
    // 响应式数据
    const categories = ref([]);
    const slideVideos = ref([]);
    const recommendedVideos = ref([]);
    const hotVideos = ref([]);
    const categoryVideosMap = ref(new Map());

    // 计算属性：显示的分类（取前几个）
    const displayCategories = computed(() => {
      return categories.value.slice(0, 4); // 显示前4个分类
    });

    // 获取分类视频的方法
    const getCategoryVideos = (categoryId) => {
      return categoryVideosMap.value.get(categoryId) || [];
    };

    // 格式化数量（如1000 -> 1万）
    const formatCount = (count) => {
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + '万';
      }
      return count.toString();
    };

    // 初始化数据
    const initData = async () => {
      try {
        // 获取分类
        const categoriesRes = await categoryApi.getCategories();
        console.log('分类数据:', categoriesRes);
        if (categoriesRes.code === 200) {
          categories.value = categoriesRes.data;
        } else {
          // 使用模拟数据
          categories.value = [
            { id: 1, name: '动画', icon: '🎬' },
            { id: 2, name: '游戏', icon: '🎮' },
            { id: 3, name: '音乐', icon: '🎵' },
            { id: 4, name: '生活', icon: '🏠' },
            { id: 5, name: '科技', icon: '💻' }
          ];
        }

        // 获取幻灯片视频
        const slideRes = await videoApi.getSlideVideos();
        console.log('幻灯片数据:', slideRes);
        if (slideRes.code === 200) {
          slideVideos.value = slideRes.data;
        } else {
          // 使用模拟数据
          slideVideos.value = [
            {
              id: 101,
              title: '【动画】最新番剧推荐！',
              cover_url: '/default-cover.svg',
              view_count: 123456,
              duration: '05:23'
            }
          ];
        }

        // 获取推荐视频
        const recommendRes = await videoApi.getRecommendedVideos({ page: 1, pageSize: 10 });
        console.log('推荐视频数据:', recommendRes);
        if (recommendRes.code === 200) {
          recommendedVideos.value = recommendRes.data.list;
        } else {
          // 使用模拟数据
          recommendedVideos.value = [
            {
              id: 201,
              title: '推荐视频1',
              cover_url: '/default-cover.svg',
              view_count: 56789,
              danmaku_count: 1234,
              nickname: 'UP主小明',
              duration: '03:45'
            },
            {
              id: 202,
              title: '推荐视频2',
              cover_url: '/default-cover.svg',
              view_count: 45678,
              danmaku_count: 890,
              nickname: 'UP主小红',
              duration: '04:12'
            }
          ];
        }

        // 获取热门视频
        const hotRes = await videoApi.getHotVideos({ page: 1, pageSize: 10 });
        console.log('热门视频数据:', hotRes);
        if (hotRes.code === 200) {
          hotVideos.value = hotRes.data.list;
        } else {
          // 使用模拟数据
          hotVideos.value = [
            {
              id: 301,
              title: '热门视频1',
              cover_url: '/default-cover.svg',
              view_count: 999999,
              danmaku_count: 12345,
              nickname: '热门UP',
              duration: '06:30'
            },
            {
              id: 302,
              title: '热门视频2',
              cover_url: '/default-cover.svg',
              view_count: 888888,
              danmaku_count: 9876,
              nickname: '人气UP',
              duration: '05:45'
            }
          ];
        }

        // 获取每个分类的视频
        for (const category of categories.value.slice(0, 4)) {
          try {
            const res = await videoApi.getVideosByCategory(category.id, { page: 1, pageSize: 5 });
            console.log(`${category.name}分类视频数据:`, res);
            if (res.code === 200) {
              categoryVideosMap.value.set(category.id, res.data.list);
            } else {
              // 使用模拟数据
              categoryVideosMap.value.set(category.id, [
                {
                  id: 1000 + category.id * 10 + 1,
                  title: `${category.name}视频1`,
                  cover_url: '/default-cover.svg',
                  view_count: 12345,
                  published_at: new Date().toISOString(),
                  nickname: `${category.name}UP主`,
                  avatar: '/default-avatar.svg',
                  duration: '02:30'
                },
                {
                  id: 1000 + category.id * 10 + 2,
                  title: `${category.name}视频2`,
                  cover_url: '/default-cover.svg',
                  view_count: 6789,
                  published_at: new Date(Date.now() - 86400000).toISOString(),
                  nickname: `${category.name}创作者`,
                  avatar: '/default-avatar.svg',
                  duration: '03:15'
                }
              ]);
            }
          } catch (error) {
            console.error(`获取${category.name}分类视频失败:`, error);
            // 出错时也使用模拟数据
            categoryVideosMap.value.set(category.id, [
              {
                id: 1000 + category.id * 10 + 1,
                title: `${category.name}视频1`,
                cover_url: '/default-cover.svg',
                view_count: 12345,
                published_at: new Date().toISOString(),
                nickname: `${category.name}UP主`,
                avatar: '/default-avatar.svg',
                duration: '02:30'
              }
            ]);
          }
        }
      } catch (error) {
        console.error('初始化数据失败:', error);
      }
    };

    // 组件挂载时获取数据
    onMounted(() => {
      initData();
    });

    return {
      categories,
      slideVideos,
      recommendedVideos,
      hotVideos,
      displayCategories,
      getCategoryVideos,
      formatCount
    };
  }
};
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 头部样式 */
.header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-top {
  display: flex;
  align-items: center;
  padding: 10px 0;
  gap: 20px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #fb7299;
}

.logo a {
  color: inherit;
  text-decoration: none;
}

.search-box {
  flex: 1;
  display: flex;
  max-width: 500px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
}

.search-btn {
  padding: 8px 16px;
  background-color: #fb7299;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.login-btn {
  padding: 8px 20px;
  background-color: #fb7299;
  color: white;
  border-radius: 4px;
  text-decoration: none;
}

/* 分类导航 */
.category-nav {
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
}

.category-list {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.category-item {
  padding: 10px 15px;
}

.category-link {
  text-decoration: none;
  color: #333;
  font-size: 14px;
  transition: color 0.3s;
}

.category-link:hover {
  color: #fb7299;
}

/* 主内容区 */
.main-content {
  padding: 20px 0;
}

.content-wrapper {
  display: flex;
  gap: 20px;
}

.main-left {
  flex: 1;
}

.main-right {
  width: 300px;
  flex-shrink: 0;
}

/* 幻灯片样式 */
.slider-section {
  margin-bottom: 20px;
}

.slider {
  position: relative;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
}

.slider-item {
  height: 100%;
}

.slider-link {
  display: block;
  height: 100%;
  position: relative;
}

.slider-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.slider-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 20px;
  color: white;
}

.slider-title {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.slider-stats {
  display: flex;
  gap: 15px;
  font-size: 14px;
}

/* 功能导航 */
.feature-nav {
  background-color: #fff;
  padding: 10px 0;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.feature-list {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0 20px;
}

.feature-item {
  margin-right: 20px;
}

.feature-link {
  text-decoration: none;
  color: #333;
  padding: 5px 10px;
  border-radius: 4px;
}

.feature-link.active {
  background-color: #fb7299;
  color: white;
}

/* 分类视频区域 */
.category-section {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  margin: 0;
  font-size: 18px;
}

.category-title-link {
  color: #333;
  text-decoration: none;
}

.more-link {
  color: #999;
  text-decoration: none;
  font-size: 14px;
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
}

/* 侧边栏样式 */
.recommend-section,
.hot-section {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  margin-bottom: 15px;
}

.sidebar-title {
  margin: 0;
  font-size: 16px;
}

.video-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 页脚样式 */
.footer {
  background-color: #2c2e3a;
  color: #999;
  padding: 40px 0;
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
}

.footer-col {
  flex: 1;
}

.footer-col h4 {
  color: #fff;
  margin-bottom: 15px;
  font-size: 16px;
}

.footer-col ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.footer-col li {
  margin-bottom: 8px;
}

.footer-col a {
  color: #999;
  text-decoration: none;
  font-size: 14px;
}

.footer-col a:hover {
  color: #fff;
}

.footer-copyright {
  text-align: center;
  font-size: 14px;
  padding-top: 20px;
  border-top: 1px solid #444;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .main-right {
    display: none;
  }
  
  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
}

@media (max-width: 768px) {
  .header-top {
    flex-wrap: wrap;
  }
  
  .search-box {
    order: 3;
    width: 100%;
    margin-top: 10px;
  }
  
  .video-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
}
</style>